import bpy
from bpy.types import NodeGroup, Node, Context
from .nodes import get_node_index_or_identifier_by

from ...addon.paths import FluidLabPaths
from ...addon.naming import FluidLabNaming
from ..functions.libraries import append_from_library



def add_node(in_node_group:NodeGroup, coords:tuple, node_type:str, sel:bool) -> Node:
    node = in_node_group.nodes.new(node_type)
    node.select = sel
    node.location = coords
    return node 


def connect_nodes(node_group:NodeGroup, node_1:Node, name_1:str, node_2:Node, name_2:str, debug:bool) -> None:
    idx_socket_n1 = get_node_index_or_identifier_by("index", "name", "outputs", node_1, name_1, debug=debug)
    idx_socket_n2 = get_node_index_or_identifier_by("index", "name", "inputs", node_2, name_2, debug=debug)
    
    if debug:
        print("idx_socket_n1, idx_socket_n2", idx_socket_n1, idx_socket_n2)
    
    if idx_socket_n1 is not None and idx_socket_n2 is not None:
        node_group.links.new(node_1.outputs[idx_socket_n1], node_2.inputs[idx_socket_n2])


def set_exposed_attributes_of_gn(gn_mod:NodeGroup, target_name:str, value, debug:bool) -> None:
    group_input = next((node for node in gn_mod.node_group.nodes if node.name.startswith("Group Input")), None)
    if group_input:
        identifier = get_node_index_or_identifier_by("identifier", "name", "outputs", group_input, target_name, debug=debug)
        if identifier is not None:
           gn_mod[identifier] = value


def append_gn(context:Context, file_name:str, gn_name:str, only_if_not_exist:bool, is_unique:bool) -> NodeGroup:

    # Para que sea un GN nuevo por cada llamada al append_gn usamos is_unique=True
    
    if is_unique:
        total = len([ng for ng in bpy.data.node_groups if ng.name.startswith(gn_name)])
        padding = len(str(total))+1
        new_name = gn_name + "_" + str(total).zfill(padding)

    # only_if_not_exist solo hace el append si no existe previamente.
    append_from_library(
        context,
        FluidLabPaths.LIBS_BLEND_PATH,
        "NodeTree",
        file_name + ".blend",
        gn_name,
        only_if_not_exist=only_if_not_exist
    )

    node_group = bpy.data.node_groups.get(gn_name)
    if node_group: 

        # Para que sean unicos necesito cambiarles el nombre también:
        if is_unique:
            node_group.name = new_name
    
        return node_group